package service

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
)

const (
	code2sessionURL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
	appID           = "wx392ec077e9eb235b"
	appSecret       = "abe73c6c580993b78b49fae1e067f673"
)

type WXLoginResp struct {
	OpenId string			`json:"openid"`
	SessionKey string		`json:"session_key"`
	UnionId string			`json:"unionid"`
	ErrCode int				`json:"errcode"`
	ErrMsg string 			`json:"errmsg"`
}

func SendWxAuthAPI (code string)(string, error) {
	url := "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"

	// 合成url, 这里的appId和secret是在微信公众平台上获取的
	url = fmt.Sprintf(url, appID, appSecret, code)

	// 创建http get请求
	resp,err := http.Get(url)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// 解析http请求中body 数据到我们定义的结构体中
	wxResp := WXLoginResp{}
	decoder := json.NewDecoder(resp.Body)
	if err := decoder.Decode(&wxResp); err != nil {
		return "", err
	}

	// 判断微信接口返回的是否是一个异常情况
	if wxResp.ErrCode != 0 {
		return "", errors.New(fmt.Sprintf("ErrCode:%d  ErrMsg:%s", wxResp.ErrCode, wxResp.ErrMsg))
	}

	return wxResp.OpenId, nil
}

func AddUser(code string) string{
	//获取openid
	openid, err := SendWxAuthAPI(code)
	if err != nil {
		return ""
	}
	fmt.Println("my openid", openid)

	//openid存储到数据库
	if SaveUserToDB(openid) == false {
		return ""
	}

	return openid
}

func UserProf(user_id string,prof string) bool{
	if AddProfToDB(user_id,prof) == false {
		return false
	}

	return true
}
